from django.shortcuts import render
from rest_framework.response import Response
from home import models,homeser
from rest_framework.views import APIView
from django.core.cache import cache
# Create your views here.
class HeadNav(APIView):
    def get(self,request):
        #首先设置改接口的缓存key
        key="headnav"
        #去缓存中读取数据
        navlist=cache.get(key)
        if navlist:
            return Response({"code":200,"msg":"ok","data":navlist})
        #展示头部导航 有效的数据 按照order排序
        navlist=models.Nav.objects.filter(position=0,flag=True).order_by("order")
        ser=homeser.NavSerializer(navlist,many=True)
        #将数据天际到缓存中
        cache.set(key,ser.data,60*60*24)
        return Response({"code":200,"msg":"ok","data":ser.data})

class FootNav(APIView):
    def get(self,request):
        # 展示尾部导航 有效的数据 按照order排序
        navlist = models.Nav.objects.filter(position=1, flag=True).order_by("order")
        ser = homeser.NavSerializer(navlist, many=True)
        return Response({"code": 200, "msg": "ok", "data": ser.data})
#banner
class Banner(APIView):
    def get(self,request):
        bannerlist=models.Banner.objects.filter(flag=True).order_by("order")
        ser=homeser.BannerSerializer(bannerlist,many=True)
        data=ser.data
        for item in data:
            item["imgurl"]="http://127.0.0.1:8000/uploads"+item["imgurl"]
        return Response({"code":200,"msg":"ok","data":data})

from rest_framework.generics import ListAPIView
class BannerList(ListAPIView):#展示轮播图
    queryset =models.Banner.objects.filter(flag=True).order_by("order")
    serializer_class = homeser.BannerSerializer

#文件上传的接口
from django.core.files.storage import default_storage
class UploadFile(APIView):
    def post(self,request):
        #获取到上传的文件  参数设置为file
        file=request.data.get("file")
        #如果没有大小和类型的限制就可以直接保存了
        #设置允许的类型
        types=['jpg','png','jpeg']
        if file.name.split(".")[-1] not in types:
            return Response({"code":201,"msg":"上传的文件类型不对"})
        #设置允许的大小 2M  b ->Kb->MB
        if file.size > 2*1024*1024:
            return Response({"code":201,"msg":"上传的文件过大"})
        #default_storage.save(上传后路径以及文件名字，获取的文件对象)
        uploadfile=default_storage.save("banner/"+file.name,file)
        #根据上传后的文件获取到路径
        url=default_storage.url(uploadfile)
        return Response({"url":url})
